package com.example.Util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.GDModel.AroundSearchInfoResData;
import com.example.GDModel.AroundSearchResData;
import com.example.GDModel.BaseResData;
import com.example.GDModel.DeleteResData;
import com.example.model.GDInfo;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by ykbboom on 2017/2/26.
 */
public class GDUtil {

    private static final Logger logger = Logger.getLogger(GDUtil.class);
    /**
     * 交换经纬度
     * */
    public static String swapLatLong(String latlong){
        String[]longlat;
        longlat = latlong.split(",");
        return longlat[1]+","+longlat[0];
    }
    /**
     * 高德云图中创建单条数据
     * */
    public static BaseResData CreateSingleData(String userPhone,String _name,String _location,String tableId){
        BaseResData baseResData = new BaseResData();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(GDInfo.GD_CREATE_SINGLE_DATA_URL);
        List<NameValuePair>params = new ArrayList<>();
        params.add(new BasicNameValuePair("key", GDInfo.GD_KEY));
        params.add(new BasicNameValuePair("tableid",tableId));
        params.add(new BasicNameValuePair("loctype","1"));//定位方式，1代表经纬度;2代表地址
        JSONObject obj = new JSONObject();
        obj.put("_name",_name);
        obj.put("_location",_location);
        obj.put("user_phone",userPhone);
        obj.put("accept",0);//0代表请求没有被接受
        params.add(new BasicNameValuePair("data",obj.toString()));
        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode()== 200){
                baseResData = JSON.parseObject(EntityUtils.toString(response.getEntity()),BaseResData.class);
                response.close();
                logger.info("添加数据结果:"+baseResData.info);
                return baseResData;
            }else {
                logger.info("请求数据失败，无法完成云图存储服务");
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                logger.info("HttpClient已关闭");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return baseResData;
    }
    /**
     * 云图更新数据
     * */
    public static BaseResData UpdateData(String _id,String tableId){
        BaseResData baseResData = new BaseResData();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(GDInfo.GD_UPDATE_DATA_URL);
        List<NameValuePair>params = new ArrayList<>();
        params.add(new BasicNameValuePair("key", GDInfo.GD_KEY));
        params.add(new BasicNameValuePair("tableid",tableId));
        params.add(new BasicNameValuePair("loctype","1"));//定位方式，1代表经纬度;2代表地址
        JSONObject obj = new JSONObject();
        obj.put("_id",_id);
//        obj.put("_name",_name);
//        obj.put("_location",_location);
        obj.put("accept",1);//请求已接受
        params.add(new BasicNameValuePair("data",obj.toString()));
        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode()== 200){
                baseResData = JSON.parseObject(EntityUtils.toString(response.getEntity()),BaseResData.class);
                response.close();
                if (baseResData.info.equals("OK")){
                    logger.info("数据更新成功:"+baseResData.info);
                    return baseResData;
                }else {
                    logger.info("数据更新失败:"+baseResData.info);
                }

            }else {
                logger.info("接口访问失败，无法完成云图更新服务");
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                logger.info("HttpClient已关闭");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return baseResData;
    }
    /**
     * 云图删除数据
     * */
    public static DeleteResData DeleteData(String ids,String tableId){
        DeleteResData deleteResData = new DeleteResData();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(GDInfo.GD_DELETE_DATA_URL);
        List<NameValuePair>params = new ArrayList<>();
        params.add(new BasicNameValuePair("key", GDInfo.GD_KEY));
        params.add(new BasicNameValuePair("tableid",tableId));
        params.add(new BasicNameValuePair("ids",ids));//多个数据id用逗号隔开
        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode()== 200){
                deleteResData = JSON.parseObject(EntityUtils.toString(response.getEntity()),DeleteResData.class);
                response.close();
                if (deleteResData.info.equals("OK")){
                    logger.info("数据删除成功:"+deleteResData.info);
                    return deleteResData;
                }else {
                    logger.info("数据删除失败:"+deleteResData.info);
                }

            }else {
                logger.info("接口访问失败，无法完成云图删除服务");
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                logger.info("HttpClient已关闭");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return deleteResData;
    }
    /**
     * 云图检索周围数据
     * */
    public static AroundSearchResData AroundSearch(String userPhone,String center,String radius,String tableId){
        AroundSearchResData aroundSearchResData = new AroundSearchResData();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(GDInfo.GD_AROUND_SEARCH_URL+"key="+ GDInfo.GD_KEY
                +"&tableid="+tableId +"&center="+center+"&radius="+radius);
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode()== 200){
                String json = EntityUtils.toString(response.getEntity());
                /**JSONObject obj = JSON.parseObject(json);
                JSONArray array = obj.getJSONArray("datas");
                List<AroundSearchInfoResData>aroundSearchInfoResDatas = new ArrayList<AroundSearchInfoResData>(JSON.parseArray(array.toJSONString(),AroundSearchInfoResData.class));
                logger.info(aroundSearchInfoResDatas);
                AroundSearchResData aroundSearchResData = new AroundSearchResData((Integer) obj.get("status")
                ,obj.getString("info"),(String) obj.get("count"),aroundSearchInfoResDatas);*/
                aroundSearchResData = JSON.parseObject(json,AroundSearchResData.class);

                if (aroundSearchResData.info.equals("OK")){
                    logger.info("数据检索成功:"+aroundSearchResData.info);
                    //屏蔽用户自己发的请求和已经被接受的请求,只返回其他用户的请求
                    Iterator<AroundSearchInfoResData>iterator = aroundSearchResData.datas.iterator();
                    while (iterator.hasNext()){
                        AroundSearchInfoResData aroundSearchInfoResData = iterator.next();
                        if (aroundSearchInfoResData.getUser_phone().equals(userPhone)||aroundSearchInfoResData.getAccept()==1){
                            iterator.remove();
                        }
                    }
                    logger.info(aroundSearchResData.toString());
                    return aroundSearchResData;
                }else {
                    logger.info("数据检索失败:"+aroundSearchResData.info);
                }

            }else {
                logger.info("接口访问失败，无法完成云图检索服务");
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                logger.info("HttpClient已关闭");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return aroundSearchResData;
    }
}
